#!/usr/bin/env python

import os, re, shlex, subprocess
from Tkinter import *
from libtovid import cli
 
class FontChooser (Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.pack()
        self.fontname = StringVar()
        self.fontname.set('helvetica')
        self.fontlist = Listbox(self)
        self.preview = Label(self, image=None)
        for font in self.get_fonts():
            self.fontlist.insert(END, font)
        self.fontlist.bind('<Button-1>', self.select)
        self.fontlist.pack()
        self.preview.pack()
 
    def select(self, event):
        self.index = self.fontlist.nearest(event.y)
        self.fontname.set(self.fontlist.get(self.index))
        self.makePreview()
 
    def get_fonts(self):
        """Return a list of font names available in ImageMagick."""
        find = "convert -list type | sed '/Path/,/---/d' | awk '{print $1}'"
        return [line.rstrip('\n') for line in os.popen(find).readlines()]

    def makePreview(self):
        """Make a BitmapImage with selected font and display in the label"""
        self.setOptions()
        self.im.run(capture=True)
        self.xbm_data = self.im.get_output()
        self.xbm_data = '"""' + self.xbm_data + '"""'
        self.bitmap = BitmapImage(data=self.xbm_data)
        self.preview.configure(image=self.bitmap)
 
    def setOptions(self):
        """Set options for imagemagick command"""
        self.im = cli.Command('convert', '-size',  '150x20', 'xc:white', '-font')
        im_opts = "-fill black -pointsize 20 -gravity center -annotate +0+0 'My title'"
        self.im.add(self.fontname.get())
        options = shlex.split(im_opts)
        for opt in options:
            self.im.add(opt)
        self.im.add('xbm:-')

if __name__ == '__main__':
    root = Tk()
    chooser = FontChooser(root)
    root.mainloop()
